<template>
      <div>
            <!-- 面包屑导航 -->
            <breadcrumb first="用户管理" second="用户列表"></breadcrumb>
            <!-- 卡片 -->
            <el-card class="box-card">
                  <!-- 搜索与添加 -->
                  <el-input v-model="queryInfo.query" 
                        placeholder="请输入内容" 
                        clearable 
                        @clear="getUserList"
                        class="search">
                        <el-button slot="append" 
                              icon="el-icon-search" 
                              @click="getUserList"></el-button>
                  </el-input>
                  <el-button type="primary" class="add" @click="isDialogVisible = true">添加用户</el-button>

                  <!-- 用户列表 -->
                  <el-table :data="userList" style="width: 100%" border stripe>
                        <el-table-column type="index" width="50"></el-table-column>
                        <el-table-column prop="username" label="姓名" width="100"></el-table-column>
                        <el-table-column prop="email" label="邮箱" min-width="150"></el-table-column>
                        <el-table-column prop="mobile" label="电话" min-width="150"></el-table-column>
                        <el-table-column prop="role_name" label="角色" min-width="100"></el-table-column>
                        <el-table-column prop="mg_state" label="状态" min-width="180">
                               <template slot-scope="scope">
                                    <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                              </template>
                        </el-table-column>
                        <el-table-column prop="role_name" label="操作" min-width="180">
                              <template slot-scope="scope">
                                    <div>
                                          <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)">
                                                <i class="el-icon-edit"></i>
                                          </el-button>
                                          <el-button size="mini" type="danger" @click="showDeleteDialog(scope.row.id)">
                                                <i class="el-icon-delete"></i>
                                          </el-button>
                                          <el-button size="mini" type="warning" @click="showSetDialogVisible(scope.row)">
                                                <i class="el-icon-s-tools"></i>
                                          </el-button>
                                    </div>
                              </template>
                        </el-table-column>
                  </el-table>

                  <!-- 分页 -->
                  <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pagenum"
                        :page-sizes="[1, 2, 5, 10]"
                        :page-size="queryInfo.pagesize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                  </el-pagination>

                  <!-- 添加用户对话框 -->
                  <el-dialog
                        title="添加用户"
                        :visible.sync="isDialogVisible"
                        width="50%"
                        @close="addDialogClose">
                        <!-- 表单主体 -->
                        <el-form :model="addForm" 
                              :rules="addRules" 
                              ref="addFormRef"
                              label-width="70px">
                              <el-form-item label="用户名" prop="username">
                                    <el-input v-model="addForm.username"></el-input>
                              </el-form-item>
                              <el-form-item label="密码" prop="password">
                                    <el-input v-model="addForm.password"></el-input>
                              </el-form-item>
                              <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="addForm.email"></el-input>
                              </el-form-item>
                              <el-form-item label="手机" prop="mobile">
                                    <el-input v-model="addForm.mobile"></el-input>
                              </el-form-item>
                        </el-form>
                        <!-- 表单footer -->
                        <span slot="footer">
                              <el-button @click="isDialogVisible = false">取 消</el-button>
                              <el-button type="primary" @click="addUser">确 定</el-button>
                        </span>
                  </el-dialog>

                  <!-- 修改用户对话框 -->
                  <el-dialog
                        title="修改用户"
                        :visible.sync="editDialogVisible"
                        width="50%"
                        @close="editDialogClose">
                        <!-- 表单主体 -->
                        <el-form :model="editForm" 
                              :rules="editRules" 
                              ref="editFormRef"
                              label-width="70px">
                              <el-form-item label="用户名" prop="username">
                                    <el-input disabled v-model="editForm.username"></el-input>
                              </el-form-item>
                              <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="editForm.email"></el-input>
                              </el-form-item>
                              <el-form-item label="手机" prop="mobile">
                                    <el-input v-model="editForm.mobile"></el-input>
                              </el-form-item>
                        </el-form>
                        <!-- 表单footer -->
                        <span slot="footer">
                              <el-button @click="editDialogVisible = false">取 消</el-button>
                              <el-button type="primary" @click="editUser()">确 定</el-button>
                        </span>
                  </el-dialog>

                  <!-- 删除用户对话框 -->
                  <el-dialog
                        title="删除用户"
                        :visible.sync="deleteDialogVisible"
                        width="35%"
                        @close="deleteUserId=''">
                        <!-- 表单主体 -->
                        <span>此操作将永久删除该用户，是否继续？</span>
                        <!-- 表单footer -->
                        <span slot="footer">
                              <el-button @click="deleteDialogVisible = false">取 消</el-button>
                              <el-button type="primary" @click="deleteUser()">确 定</el-button>
                        </span>
                  </el-dialog>

                  <!-- 分配用户权限对话框 -->
                  <el-dialog
                        title="分配用户权限"
                        :visible.sync="setDialogVisible"
                        width="400px"
                        @close="selectedRole=''">
                        <!-- 表单主体 -->
                        <p>当前用户：{{this.setUser.username}}</p>
                        <p>当前角色：{{this.setUser.role_name}}</p>
                        分配新角色
                        <el-select v-model="selectedRole" placeholder="请选择">
                              <el-option
                                    v-for="item in roleList"
                                    :key="item.id"
                                    :label="item.roleName"
                                    :value="item.id">
                              </el-option>
                        </el-select>
                        <!-- 表单footer -->
                        <span slot="footer">
                              <el-button @click="setDialogVisible = false">取 消</el-button>
                              <el-button type="primary" @click="saveUserInfo()">确 定</el-button>
                        </span>
                  </el-dialog>

            </el-card>
      </div>
</template>

<script>
import Breadcrumb from './breadcrumb'
export default {
      components:{
            breadcrumb: Breadcrumb
      },
      data(){
            var checkEmail = (rule, value, callback) => {
                  const regEmail = /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
                  if (!regEmail.test(value)) {
                        return callback(new Error('请输入正确的邮箱'));
                  }
                  return callback();
            };
            var checkMobile = (rule, value, callback) => {
                  const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
                  if (!regMobile.test(value)) {
                        return callback(new Error('请输入正确的手机号码'));
                  }
                  return callback();
            };
            return {
                  queryInfo: {
                        query: '',
                        pagenum: 1, //当前页码
                        pagesize: 2 // 当前每页显示页数
                  },
                  total: null,
                  userList: [],
                  isDialogVisible: false,   //控制添加用户对话框的显示与隐藏
                  addForm: {  //添加用户表单
                        username: '',
                        password: '',
                        email: '',
                        mobile: '',
                  }, 
                  addRules: { //添加用户表单规则
                        username: [
                              {required: true, message:'请输入用户名', trigger: 'blur'},
                              {min: 3, max: 10, message:'用户名长度为3-10', trigger: 'blur'},
                        ],
                        password: [
                              {required: true, message:'请输入密码', trigger: 'blur'},
                              {min: 6, max: 15, message:'用户名长度为6-15', trigger: 'blur'},
                        ],
                        email: [
                              {required: true, message:'请输入邮箱', trigger: 'blur'},
                              {validator: checkEmail, trigger: 'blur'}
                        ],
                        mobile: [
                              {required: true, message:'请输入手机', trigger: 'blur'},
                              {min: 11, max: 11, message:'请正确输入手机号码', trigger: 'blur'},
                              {validator: checkMobile, trigger: 'blur'}
                        ],
                  }, 
                  editDialogVisible: false, //控制修改用户信息对话框显示与不显示
                  editForm: {
                        username: '',
                        email: '',
                        mobile: '',
                  },
                  editRules: { //添加用户表单规则
                        email: [
                              {required: true, message:'请输入邮箱', trigger: 'blur'},
                              {validator: checkEmail, trigger: 'blur'}
                        ],
                        mobile: [
                              {required: true, message:'请输入手机', trigger: 'blur'},
                              {min: 11, max: 11, message:'请正确输入手机号码', trigger: 'blur'},
                              {validator: checkMobile, trigger: 'blur'}
                        ],
                  },
                  deleteDialogVisible: false,   //控制删除用户对话框的显示与隐藏
                  deleteUserId: '', //删除用户id
                  setDialogVisible: false,      //分配用户权限对话框是否显示
                  setUser: '',      //分配权限用户
                  roleList: [],
                  selectedRole: '',
            }
      },
      created(){
            this.getUserList();
      },
      methods: {
            async getUserList(){
                  const {data: res} = await this.$http.get('/users', { params: this.queryInfo});
                  if(res.meta.status !== 200){
                        return this.$message.error('获取用户信息失败');
                  }
                  this.userList = res.data.users;
                  this.total = res.data.total;
            },
            // 切换用户状态
            togglrState(userId){
                  this.userList.forEach(item => {
                        if(item.id == userId){
                              item.mg_state = !item.mg_state;
                        }
                  })
            },
            // 调整每页显示页数
            handleSizeChange(newSize){
                  this.queryInfo.pagesize = newSize;
                  this.getUserList();
            },
            // 监听页码改变
            handleCurrentChange(page){
                  this.queryInfo.pagenum = page;
                  this.getUserList();
            },
            //监听Switch用户状态改变
            async userStateChange(userinfo){
                  const {data: res} = await this.$http.put(`/users/${userinfo.id}/state/${userinfo.mg_state}`);
                  if(res.meta.status !== 200){
                        userinfo.mg_state = !userinfo.mg_state;
                        return this.$message.error('更新用户状态失败');
                  }else{
                        return this.$message.success('更新用户状态成功');
                  }
            },
            //重置添加用户对话框
            addDialogClose(){
                  this.$refs.addFormRef.resetFields();
            },
            //添加用户
            addUser(){
                  this.$refs.addFormRef.validate(async valid => {
                        if(valid){
                              const {data: res} = await this.$http.post('/users', this.addForm );
                              if(res.meta.status !== 201){
                                    return this.$message.error(res.meta.msg);
                              }
                              this.isDialogVisible = false;
                              return this.$message.success('添加用户成功');
                        }else{
                              return ;
                        }
                  })
            },
            //展示修改用户信息对话框
            async showEditDialog(id){
                  const {data: res} = await this.$http.get('/users/' + id);
                  if(res.meta.status !== 200){
                        return this.$message.error('获取用户信息失败');
                  }
                  this.editForm = res.data;
                  this.editDialogVisible = true;
            },
            //重置修改用户信息对话框
            editDialogClose(){
                  this.$refs.editFormRef.resetFields();
            },
            //修改用户信息
            editUser(){
                  this.$refs.editFormRef.validate(async valid => {
                        if(valid){
                              const {data: res} = await this.$http.put('/users/'+this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile});
                              if(res.meta.status !== 200){
                                    return this.$message.error('修改用户信息失败');
                              }
                              this.editDialogVisible = false;
                              this.getUserList();
                              return this.$message.success('修改用户信息成功');
                              
                        }
                  })
            },
            //展示删除用户对话框
            showDeleteDialog(id){
                  this.deleteDialogVisible = true;
                  this.deleteUserId = id;
            },
            //删除用户信息
            async deleteUser(){
                  const {data: res} = await this.$http.delete('/users/' + this.deleteUserId);
                  if(res.meta.status !== 200){
                        return this.$message.error('删除用户失败');
                  }
                  this.getUserList();
                  this.deleteUserId = '';
                  this.deleteDialogVisible = false;
                  return this.$message.success('删除用户成功');
            },
            //展示角色分配弹出框
            async showSetDialogVisible(role){
                  const {data: res} = await this.$http.get('/roles');
                  if( res.meta.status !== 200)  return this.$message.error(res.meta.msg);
                  this.roleList = res.data;
                  console.log(res.data)
                  this.setUser = role;
                  this.setDialogVisible = true;
            },
            //调用api分配角色
            async saveUserInfo(){
                  if(!this.selectedRole){
                        return this.$message.error('请选择分配的角色');
                  }
                  const {data : res} = await this.$http.put(`/users/${this.setUser.id}/role`, { rid: this.selectedRole });
                  this.setDialogVisible = false;
                  if(res.meta.status !== 200){
                        return this.$message.error(res.meta.msg);
                  }
                  this.getUserList();
                  return this.$message.success(res.meta.msg);
            }
      }
}
</script>

<style scoped>
.search{
      width: 300px;
}
.add{
      margin-left: 20px;
}
.el-table{
      margin-top: 15px;
      font-size: 13px;
}
.el-pagination{
      margin-top: 15px;
}
.el-select>>>.el-input__inner{
      height: 30px      !important;
      width: 150px;
      line-height: 30px;
}
.el-select>>>.el-icon-arrow-up{
      line-height: 30px;
}
</style>